package com.zx.mes.hyl.security.browser.authentication;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zx.mes.hyl.security.core.properties.LoginResponseType;
import com.zx.mes.hyl.security.core.properties.SecurityProperties;
import com.zx.mes.hyl.security.core.support.SimpleResponse;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 浏览器环境下登录成功后的处理器
 * SavedRequestAwareAuthenticationSuccessHandler security 默认登录成功处理器  将其重写
 * @author hyl
 * @date 2018-5-30
 */
@SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
@Component("longAuthenticationSuccessHandler")
public class LongAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler{

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private SecurityProperties securityProperties;

    private RequestCache requestCache = new HttpSessionRequestCache();

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {

        logger.info("登录成功!");

        /* 如查是以json返回登录信息
        *  如果是redirect 直接跳到先前访问的地址  如: http://localhost:8500/test/say  登录后，再到 http://localhost:8500/test/say
        * **/
        if (LoginResponseType.JSON.equals(securityProperties.getBrowser().getSignInResponseType())) {
            response.setContentType("application/json;charset=UTF-8");
///            String type = authentication.getClass().getSimpleName();
            response.getWriter().write(objectMapper.writeValueAsString(new SimpleResponse(authentication)));
        } else {
            /* 如果设置了long.security.browser.singInSuccessUrl,总是跳到设置的地址上
               如果没设置，则尝试跳转到登录之前的地址上，如果登录前访问地址为空，则跳到网站根路径上
              **/
            if (StringUtils.isNotBlank(securityProperties.getBrowser().getSignInSuccessUrl())) {
                requestCache.removeRequest(request, response);
                setAlwaysUseDefaultTargetUrl(true);
                /** 见其英文文档 **/
                setDefaultTargetUrl(securityProperties.getBrowser().getSignInSuccessUrl());
            }
            super.onAuthenticationSuccess(request, response, authentication);
        }
    }
}
